package com.shwread.android.qysw.activity.task;

import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.GlideUtil;
import com.NewActionHelp;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.views.multi_image_selector.MultiImageSelectorActivity;
import com.google.gson.reflect.TypeToken;
import com.image_see.ImageSeeActivity;
import com.shwread.android.qysw.adapter.TaskAdapter;
import com.shwread.android.qysw.bean.task.OrganizeActivityBean;
import com.shwread.android.qysw.bean.task.SignBean;
import com.shwread.android.qysw10000241.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.util.NetUtil;
import com.ui.dialog.CustomDialog;

import org.apache.http.Header;

import java.io.FileNotFoundException;
import java.lang.reflect.Type;
import java.util.ArrayList;

import logic.util.Util;
import logic.util.Utils;

/**
 * 组织任务详情
 */
public class OrganizationTaskDetailActivity extends BaseActicity {
    private static final int REQUEST_IMAGE = 7;
    private ArrayList<String> selectedPictureAll = new ArrayList<>();

    /**
     * 活动名称
     */
    private TextView tvTaskName;
    /**
     * 分项
     */
    private TextView tvTaskSubItem;
    /**
     * 类别
     */
    private TextView tvTaskCategory;
    /**
     * 指数类型
     */
    private TextView tvTaskType;
    /**
     * 活动分值
     */
    private TextView tvTaskValue;
    /**
     * 开始时间
     */
    private TextView tvTaskStartTime;
    /**
     * 结束时间
     */
    private TextView tvTaskEndTime;
    /**
     * 活动地点
     */
    private TextView tvTaskAddress;
    /**
     * 联系人
     */
    private TextView tvTaskContacts;
    /**
     * 联系电话
     */
    private TextView tvTaskPhoneNumber;
    /**
     * 活动说明
     */
    private TextView tvTaskIllustrate;
    /**
     * 签到情况
     */
    private LinearLayout llTaskSignStatus;
    /**
     * 签到情况
     */
    private TextView tvTaskSignStatus;
    /**
     * 签到时间
     */
    private LinearLayout llTaskSignTime;
    /**
     * 签到时间
     */
    private TextView tvTaskSignTime;
    /**
     * 上传凭证条目
     */
    private LinearLayout llUploadTestimony;
    /**
     * 上传凭证
     */
    private ImageView imgUploadTestimony;
    /**
     * 凭证条目
     */
    private LinearLayout llTaskTestimony;
    /**
     * 凭证
     */
    private ImageView imgTaskTestimony;
    /**
     * 签到
     */
    private Button btTaskSign;
    /**
     * 上传凭证
     */
    private Button btTaskUpload;
    /**
     * 任务完成情况
     */
    private ImageView imgTaskStatus;

    /**
     * 详情数据
     */
    private OrganizeActivityBean taskBean;
    /**
     * 定位服务对象
     */
    private AMapLocationClient locationClient;
    private int taskId;
    /**
     * 凭证文件路径
     */
    private String imgPath;

    @Override
    protected void initTopBar() {
        setTitle("组织活动任务");
        enableNavLeftImg();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_organization_task_detail);
    }

    @Override
    protected void initView() {
        tvTaskName = findViewByID(R.id.tv_task_name);
        tvTaskSubItem = findViewByID(R.id.tv_task_sub_item);
        tvTaskCategory = findViewByID(R.id.tv_task_category);
        tvTaskType = findViewByID(R.id.tv_task_type);
        tvTaskValue = findViewByID(R.id.tv_task_value);
        tvTaskStartTime = findViewByID(R.id.tv_task_start_time);
        tvTaskEndTime = findViewByID(R.id.tv_task_end_time);
        tvTaskAddress = findViewByID(R.id.tv_task_address);
        tvTaskContacts = findViewByID(R.id.tv_task_contacts);
        tvTaskPhoneNumber = findViewByID(R.id.tv_task_phone_number);
        tvTaskIllustrate = findViewByID(R.id.tv_task_illustrate);
        llTaskSignStatus = findViewByID(R.id.ll_task_sign_status);
        tvTaskSignStatus = findViewByID(R.id.tv_task_sign_status);
        llTaskSignTime = findViewByID(R.id.ll_task_sign_time);
        tvTaskSignTime = findViewByID(R.id.tv_task_sign_time);
        llUploadTestimony = findViewByID(R.id.ll_upload_testimony);
        imgUploadTestimony = findViewByID(R.id.img_upload_testimony);
        llTaskTestimony = findViewByID(R.id.ll_task_testimony);
        imgTaskTestimony = findViewByID(R.id.img_task_testimony);
        btTaskSign = findViewByID(R.id.bt_task_sign);
        btTaskUpload = findViewByID(R.id.bt_task_upload);
        imgTaskStatus = findViewByID(R.id.img_task_status);
    }

    @Override
    protected void initAdapter() {
        btTaskSign.setOnClickListener(this);
        btTaskUpload.setOnClickListener(this);
    }

    @Override
    protected void initDates() {
        taskId = getIntent().getIntExtra("taskId", 0);
        NewActionHelp.getOrganActivityInfo(this, taskId, new ObjectHttpResponseHandler<OrganizeActivityBean>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("sss", "失败--" + s);
            }

            @Override
            public void onSuccess(int i, Header[] headers, OrganizeActivityBean organizeActivityBean, String s) {
                Log.e("sss", "成功--" + s);
                taskBean = organizeActivityBean;
                setView();
            }

            @Override
            public Type getType() {
                return new TypeToken<OrganizeActivityBean>() {
                }.getType();
            }
        });
    }

    private void setView() {
        if (taskBean == null) {
            return;
        }
        tvTaskName.setText(taskBean.getActivityName());
        tvTaskSubItem.setText(taskBean.getIndexName());
        tvTaskCategory.setText(taskBean.getKindName());
        tvTaskType.setText(taskBean.getIndexType());
        tvTaskIllustrate.setText(taskBean.getActivityExplain());
        tvTaskValue.setText(String.format("%s分",Utils.getScore(taskBean.getActivityScore())));

        if ("底线指数".equals(taskBean.getIndexType())) {
            findViewByID(R.id.ll_task_start_time).setVisibility(View.GONE);
            findViewByID(R.id.ll_task_end_time).setVisibility(View.GONE);
            findViewByID(R.id.ll_task_address).setVisibility(View.GONE);
            findViewByID(R.id.ll_task_contacts).setVisibility(View.GONE);
            findViewByID(R.id.ll_task_phone_number).setVisibility(View.GONE);
            llTaskSignStatus.setVisibility(View.GONE);
            llTaskSignTime.setVisibility(View.GONE);
            llUploadTestimony.setVisibility(View.GONE);
            llTaskTestimony.setVisibility(View.GONE);
            btTaskSign.setVisibility(View.GONE);
            btTaskUpload.setVisibility(View.GONE);
            return;
        }
        tvTaskStartTime.setText(TaskAdapter.getTime(taskBean.getStartTime()));
        tvTaskEndTime.setText(TaskAdapter.getTime(taskBean.getEndTime()));
        tvTaskAddress.setText(taskBean.getSignAddress());
        tvTaskContacts.setText(taskBean.getLinkmanName());
        tvTaskPhoneNumber.setText(taskBean.getLinkmanPhone());

        switch (taskBean.getActivityStatus()) {//1|2|3|4 未发布|进行中|已完成|已取消
            case "2"://进行中
                imgTaskStatus.setImageResource(R.drawable.task_ing);
                if ("y".equals(taskBean.getIsSign())) {//需要签到
                    signShow();
                } else {//不需要签到
                    llTaskSignStatus.setVisibility(View.GONE);
                    llTaskSignTime.setVisibility(View.GONE);
                    btTaskSign.setVisibility(View.GONE);
                    haveUpload();
                }
                break;
            case "3"://已完成
                imgTaskStatus.setImageResource(R.drawable.task_complete);
                llUploadTestimony.setVisibility(View.GONE);
                String url = taskBean.getPostActUserInfo().getVoucherData();
                if (url != null) {
                    llTaskTestimony.setVisibility(View.VISIBLE);
                    GlideUtil.load(this, url, imgTaskTestimony);
                } else {
                    llTaskTestimony.setVisibility(View.GONE);
                }
                btTaskSign.setVisibility(View.GONE);
                if ("y".equals(taskBean.getIsSign())) {//需要签到
                    if ("y".equals(taskBean.getPostActUserInfo().getIsSign())) {//已签到
                        llTaskSignStatus.setVisibility(View.GONE);
                        llTaskSignTime.setVisibility(View.VISIBLE);
                        tvTaskSignTime.setText(TaskAdapter.getTime(taskBean.getPostActUserInfo().getSignTime()));
                    } else {//未签到
                        llTaskSignStatus.setVisibility(View.VISIBLE);
                        llTaskSignTime.setVisibility(View.GONE);
                        tvTaskSignStatus.setText("未签到");
                    }
                } else {//不需要签到
                    llTaskSignStatus.setVisibility(View.GONE);
                    llTaskSignTime.setVisibility(View.GONE);
                }
                break;
            case "4"://已取消
                imgTaskStatus.setImageResource(R.drawable.task_cancel);
                llUploadTestimony.setVisibility(View.GONE);
                llTaskTestimony.setVisibility(View.GONE);
                btTaskSign.setVisibility(View.GONE);
                llTaskSignStatus.setVisibility(View.GONE);
                llTaskSignTime.setVisibility(View.GONE);
                tvTaskSignStatus.setText("未签到");
                break;
        }
    }

    /**
     * 签到状态显示和隐藏
     */
    private void signShow() {
        if ("y".equals(taskBean.getPostActUserInfo().getIsSign())) {//已签到
            btTaskSign.setBackgroundResource(R.drawable.buttonbg_gray);
            btTaskSign.setEnabled(false);
            btTaskSign.setText("已签到");
            llTaskSignStatus.setVisibility(View.GONE);
            llTaskSignTime.setVisibility(View.VISIBLE);
            tvTaskSignTime.setText(TaskAdapter.getTime(taskBean.getPostActUserInfo().getSignTime()));
            haveUpload();
        } else {//未签到
            btTaskSign.setBackgroundResource(R.drawable.btn_red);
            btTaskSign.setEnabled(true);
            btTaskSign.setText("签到");
            tvTaskSignStatus.setText("未签到");
            llTaskSignStatus.setVisibility(View.VISIBLE);
            llTaskSignTime.setVisibility(View.GONE);
            llUploadTestimony.setVisibility(View.GONE);
            llTaskTestimony.setVisibility(View.GONE);
        }
    }

    /**
     * 是否需要上传
     */
    private void haveUpload() {
        if ("y".equals(taskBean.getIsVoucher())) {//需要上传
            btTaskSign.setVisibility(View.GONE);
            String url = taskBean.getPostActUserInfo().getVoucherData();
            if (url != null) {//已上传
                llUploadTestimony.setVisibility(View.GONE);
                llTaskTestimony.setVisibility(View.VISIBLE);
                GlideUtil.load(this, url, imgTaskTestimony);
            } else {//未上传
                llUploadTestimony.setVisibility(View.VISIBLE);
                llTaskTestimony.setVisibility(View.GONE);
                btTaskUpload.setVisibility(View.VISIBLE);
            }
        } else {//不需要上传
            llUploadTestimony.setVisibility(View.GONE);
            llTaskTestimony.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initListener() {
        tvTaskSignStatus.setOnClickListener(this);
        imgUploadTestimony.setOnClickListener(this);
        imgTaskTestimony.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.bt_task_sign://签到
                startLocation();
                break;
            case R.id.bt_task_upload://上传凭证
                uploadImg();
                break;
            case R.id.img_upload_testimony://选择凭证
                selectImg();
                break;
            case R.id.img_task_testimony://查看凭证
                Intent intent = new Intent(this, ImageSeeActivity.class);
                ArrayList<String> urlList = new ArrayList<>();
                urlList.add(taskBean.getPostActUserInfo().getVoucherData());
                intent.putStringArrayListExtra("urlList", urlList);
                startActivity(intent);
                break;
        }
    }

    /**
     * 定位
     */
    private void startLocation() {
        if (!NetUtil.isNetworkConnected(this)) {//无网络
            new NoNetDialog(this).show();
            return;
        }
        if (!Util.gpsIsOpen(this)) {//gps未打开
            new CustomDialog.Builder(this)
                    .setMessage("打开“GPS”以便准确获取当前位置")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create().show();
            return;
        }
        progressDialog.show();
        btTaskSign.setEnabled(false);
        locationClient = new AMapLocationClient(this);
        AMapLocationClientOption aMapLocationClientOption = new AMapLocationClientOption()
                .setOnceLocation(true)
                .setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)  // 设置定位模式为高精度模式
                .setNeedAddress(true)//设置定位同时是否需要返回地址描述
                .setInterval(1000 * 60);
        locationClient.setLocationOption(aMapLocationClientOption);//自定义调用间隔
        // 设置定位监听
        locationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                double lon = aMapLocation.getLongitude();
                double lat = aMapLocation.getLatitude();
                Log.e("sss", "lat:" + lat + "-----lon:" + lon + "type--" + aMapLocation.getLocationType());
                signIn(lon, lat);
                locationClient.stopLocation();//停止定位服务
            }
        });
        locationClient.startLocation();
    }

    /**
     * 活动签到
     *
     * @param lon 经度
     * @param lat 纬度
     */
    private void signIn(double lon, double lat) {
        NewActionHelp.organActivitySign(this, taskId, lon, lat, new ObjectHttpResponseHandler<SignBean>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("sss", "失败--" + s);
                progressDialog.dismiss();
                Utils.showToast(OrganizationTaskDetailActivity.this, "签到失败");
            }

            @Override
            public void onSuccess(int i, Header[] headers, SignBean signBean, String s) {
                Log.e("sss", "成功--" + s);
                progressDialog.dismiss();
                Utils.showToast(OrganizationTaskDetailActivity.this, signBean.getSign_rst() + "");
                switch (signBean.getSign_status()) {
                    case 0://已签到
                    case 1://签到成功
                        btTaskSign.setBackgroundResource(R.drawable.buttonbg_gray);
                        btTaskSign.setText("已签到");
                        llTaskSignStatus.setVisibility(View.GONE);
                        llTaskSignTime.setVisibility(View.VISIBLE);
                        tvTaskSignTime.setText(TaskAdapter.getTime(System.currentTimeMillis() / 1000));
                        haveUpload();
                        break;
                    case 2://没有在签到范围内
                        btTaskSign.setEnabled(true);
                        break;
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<SignBean>() {
                }.getType();
            }
        });
    }

    /**
     * 选择凭证图片
     */
    private void selectImg() {
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        // 默认选择
        if (selectedPictureAll != null && selectedPictureAll.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE && data != null) {//选择图片回调
            ArrayList<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            selectedPictureAll.addAll(mSelectPath);
            for (String path : mSelectPath) {
                Log.e("sss", "图片地址---" + path);
                GlideUtil.loadLocalUrl(this, path, imgUploadTestimony, null);
                imgPath = path;
            }
        }
    }

    /**
     * 上传凭证
     */
    private void uploadImg() {
        if (imgPath == null) {
            Utils.showToast(this, "请先选择凭证文件");
            return;
        }
        if (!NetUtil.isNetworkConnected(this)) {//无网络
            new NoNetDialog(this).show();
            return;
        }
        btTaskUpload.setEnabled(false);
        try {
            NewActionHelp.uploadVoucher(this, taskId, imgPath, 1, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                    btTaskUpload.setEnabled(true);
                    Utils.showToast(OrganizationTaskDetailActivity.this,"上传失败");
                    Log.e("sss", "失败--" + s);
                }

                @Override
                public void onSuccess(int i, Header[] headers, String s) {
                    btTaskUpload.setBackgroundResource(R.drawable.buttonbg_gray);
                    btTaskUpload.setText("上传成功");
                    Log.e("sss", "成功--" + s);
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            btTaskUpload.setEnabled(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationClient != null) {
            locationClient.onDestroy();//销毁定位服务
        }
        NewActionHelp.cancel(this);
    }
}
